<template>
  <div class="mine-layout pt-3">
    <MaProTable
      ref="proTableRef"
      :options="options"
      :schema="schema"
      @search-submit="(form: any) => {
      console.log( JSON.stringify(form),'form搜索')
    }"
    >
      <template #tableTop>
        <tabs :items="tabsList" v-model="activeName"></tabs>
      </template>
      <template #toolbarLeft>
        <el-button
          type="danger"
          plain
          :disabled="selections.length < 1"
          @click="handleDelete"
        >
          批量删除
        </el-button>
        <el-button
          type="primary"
          @click="
            () => {
              maDialog.setTitle('添加商品');
              maDialog.open({ formType: 'add' });
            }
          "
        >
          添加
        </el-button>
      </template>
    </MaProTable>
    <component :is="maDialog.Dialog">
      <template #default="{ formType, data }">
        <!-- 新增、编辑表单 -->
        <dataForm
          ref="formRef"
          :form-type="formType"
          :data="data"
        />
      </template>
    </component>
  </div>
</template>
<script setup lang="tsx">
import type {
  MaProTableExpose,
  MaProTableOptions,
  MaProTableSchema,
} from "@mineadmin/pro-table";
import type { Ref } from "vue";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import { deleteByIds } from "~/base/api/user";
import getSearchItems from "./getSearchItems.tsx";
import getTableColumns from "./getTableColumns.tsx";
import useDialog from "@/hooks/useDialog.ts";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import tabs from "@/components/y-tabs/index.vue";

import dataForm from "./data/form.vue";
import {goodslistall} from "~/base/api/product.ts";

defineOptions({ name: "permission:user" });

const proTableRef = ref<MaProTableExpose>() as Ref<MaProTableExpose>;
const formRef = ref();
const selections = ref<any[]>([]);
const msg = useMessage();
let activeName = ref<any>("");
const tabsList = reactive([
  {
    label: "测试1",
    name: "",
  },
  {
    label: "测试2",
    name: "1",
  },
  {
    label: "测试3",
    name: "2",
  },
]);
// 弹窗配置
const maDialog: UseDialogExpose = useDialog({
  lgWidth: "750px",
  // 保存数据
  ok: ({ formType }, okLoadingState: (state: boolean) => void) => {
    okLoadingState(true);
    if (["add", "edit"].includes(formType)) {
      const elForm = formRef.value.maForm.getElFormRef();
      // 验证通过后
      elForm
        .validate()
        .then(() => {
          switch (formType) {
            // 新增
            case "add":
              formRef.value
                .add()
                .then((res: any) => {
                  res.code === ResultCode.SUCCESS
                    ? msg.success('添加成功')
                    : msg.error(res.message);
                  maDialog.close();
                  proTableRef.value.refresh();
                })
                .catch((err: any) => {
                  msg.alertError(err);
                });
              break;
            // 修改
            case "edit":
              formRef.value
                .edit()
                .then((res: any) => {
                  res.code === 200
                    ? msg.success('修改成功')
                    : msg.error(res.message);
                  maDialog.close();
                  proTableRef.value.refresh();
                })
                .catch((err: any) => {
                  msg.alertError(err);
                });
              break;
          }
        })
        .catch();
    }
    okLoadingState(false);
  },
});

// 参数配置
const options = ref<MaProTableOptions>({
  // 表格距离底部的像素偏移适配
  adaptionOffsetBottom: 210,
  header: { show: false },
  // 表格参数
  tableOptions: {
    on: {
      // 表格选择事件
      onSelectionChange: (selection: any[]) => (selections.value = selection),
    },
  },
  // 搜索参数
  searchOptions: { fold: true},
  // 搜索表单参数
  // searchFormOptions: { labelWidth: "90px" },
  // 请求配置
  requestOptions: {
    api: goodslistall,
    requestPage:{ pageName: 'page', sizeName: 'limit', size: 10 },
    response: { totalKey: 'count', dataKey: 'data'}
  },
});
// 架构配置
const schema = ref<MaProTableSchema>({
  // 搜索项
  searchItems: getSearchItems(''),
  // 表格列
  tableColumns: getTableColumns(maDialog, formRef),
});

// 批量删除
function handleDelete() {
  const ids = selections.value.map((item: any) => item.id);
  msg.confirm('是否删除').then(async () => {
    const response = await deleteByIds(ids);
    if (response.code === ResultCode.SUCCESS) {
      msg.success('删除成功');
      await proTableRef.value.refresh();
    }
  });
}
</script>

<style scoped lang="scss"></style>
